package com.fin.zw.intelligentbot.service;

import com.fin.zw.intelligentbot.entity.QTaskCustomer;
import com.fin.zw.intelligentbot.entity.TaskCustomer;
import com.fin.zw.intelligentbot.enums.Sex;
import com.fin.zw.intelligentbot.enums.TaskStatus;
import com.fin.zw.intelligentbot.model.request.DialLogRequest;
import com.fin.zw.intelligentbot.model.response.DialLogResponse;
import com.fin.zw.intelligentbot.model.response.TaskLogResponse;
import com.fin.zw.intelligentbot.model.session.SessionModel;
import com.fin.zw.intelligentbot.repository.TaskCustomerRepository;
import com.fin.zw.intelligentbot.util.CSVUtils;
import com.fin.zw.intelligentbot.util.FileUtil;
import com.fin.zw.intelligentbot.util.Snowflake;
import com.google.common.collect.Lists;
import com.querydsl.core.BooleanBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("dialLogService")
public class DialLogService {
    @Autowired
    private TaskCustomerRepository cdrService;

    @Autowired
    private Snowflake snowflake;

    @Value("${root.template}")
    private String rootPath;


    /**
     * 查询日志信息(分页)
     *
     * @param pageable
     * @param request
     * @param session
     * @return
     */
    public Page<DialLogResponse> fetchPage(Pageable pageable,
                                           DialLogRequest request, SessionModel session) {
        BooleanBuilder builder = getBooleanBuilder(session, request);
        if (request.getStatus() == null) {
            builder.and(QTaskCustomer.taskCustomer.status.notIn(TaskStatus.NEW, TaskStatus.READY));
        }
        Page<TaskCustomer> customerPage = cdrService.findAll(builder, pageable);
        Page<DialLogResponse> page = customerPage.map(customer -> {
            return getDialLogResponse(customer);
        });
        return page;
    }


    /**
     * 根据id查询日志
     *
     * @param pageable
     * @param taskId
     * @return
     */
    public Page<TaskLogResponse> fetchPageByTaskId(Pageable pageable,
                                                   String taskId, String name, String phone, TaskStatus status) {
        BooleanBuilder builder = new BooleanBuilder();
        QTaskCustomer qTaskCustomer = QTaskCustomer.taskCustomer;
        builder.and(qTaskCustomer.dialTask.id.eq(taskId));
        if (StringUtils.isNotEmpty(name)) {
            builder.and(qTaskCustomer.name.eq(name));
        }
        if (StringUtils.isNotEmpty(phone)) {
            builder.and(qTaskCustomer.phone.eq(phone));
        }
        if (status != null) {
            builder.and(qTaskCustomer.status.eq(status));
        }
        Page<TaskCustomer> customerPage = cdrService.findAll(builder, pageable);
        Page<TaskLogResponse> page = customerPage.map(customer -> {
            TaskLogResponse taskLogResponse = new TaskLogResponse();
            BeanUtils.copyProperties(customer, taskLogResponse);
            taskLogResponse.setSex(customer.getSex().toString());
            taskLogResponse.setStatus(customer.getStatus().toString());
            return taskLogResponse;
        });
        return page;
    }

    public DialLogResponse getDialLogResponse(TaskCustomer customer) {
        DialLogResponse logResponse = new DialLogResponse();
        BeanUtils.copyProperties(customer, logResponse);
        if (Objects.nonNull(customer.getRobotInfo())) {
            logResponse.setBotId(customer.getRobotInfo().getId());
            logResponse.setBotName(customer.getRobotInfo().getName());
        }
        if (customer.getAttitude() != null) {
            logResponse.setAttitude(customer.getAttitude().getName());
        }
//        if (Objects.nonNull(customer.getDialTask())) {
//            logResponse.setTaskId(customer.getDialTask().getId());
//            logResponse.setTaskName(customer.getDialTask().getName());
//        }
        logResponse.setSex(customer.getSex().toString());
        logResponse.setStatus(customer.getStatus().toString());
        if (Objects.nonNull(customer.getDialogRecord())) {
            logResponse.setRecordFile(customer.getDialogRecord());
        }
        if (Objects.nonNull(customer.getDialogContent())) {
            logResponse.setContentFile(customer.getDialogContent());
        }
        return logResponse;
    }

    public List<DialLogResponse> fetch(DialLogRequest request, SessionModel session) {
        BooleanBuilder builder = getBooleanBuilder(session, request);
        if (StringUtils.isNotEmpty(request.getTaskId())) {
            builder.and(QTaskCustomer.taskCustomer.dialTask.id.eq(request.getTaskId()));
        }
        Iterator<TaskCustomer> iterator = cdrService.findAll(builder).iterator();
        List<TaskCustomer> taskCustomers = Lists.newArrayList(iterator);
        List<DialLogResponse> list = taskCustomers.stream().map(c -> {
            return getDialLogResponse(c);
        }).collect(Collectors.toList());
        return list;
    }


    public BooleanBuilder getBooleanBuilder(SessionModel session, DialLogRequest request) {
        BooleanBuilder builder = new BooleanBuilder();
        QTaskCustomer qTaskCustomer = QTaskCustomer.taskCustomer;
        if (StringUtils.isNotEmpty(request.getId())) {
            builder.and(qTaskCustomer.id.eq(request.getId()));
        }
        if (StringUtils.isNotEmpty(session.getCompanyId())) {
            builder.and(qTaskCustomer.company.id.eq(session.getCompanyId()));
        }
        if (StringUtils.isNotEmpty(request.getAttitudeId())) {
            builder.and(qTaskCustomer.attitude.id.eq(request.getAttitudeId()));
        }
        if (StringUtils.isNotEmpty(request.getPhone())) {
            builder.and(qTaskCustomer.phone.eq(request.getPhone()));
        }
        if (StringUtils.isNotEmpty(request.getSceId())) {
            builder.and(qTaskCustomer.dialTask.scene.id.eq(request.getSceId()));
        }
        if (request.getBillTime() != null) {
            builder.and(qTaskCustomer.billTime.goe(request.getBillTime()));
        }
        if (request.getStatus() != null) {
            builder.and(qTaskCustomer.status.eq(request.getStatus()));
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            builder.and(qTaskCustomer.startTime.between(request.getStartTime(), request.getEndTime()));
        }
        return builder;
    }


    /**
     * 日志打包下载
     *
     * @param request
     * @param session
     */
    public void downloadLog(HttpServletResponse response, DialLogRequest request, SessionModel session) throws Exception {
        BooleanBuilder builder = getBooleanBuilder(session, request);
        if (StringUtils.isNotEmpty(request.getTaskId())) {
            builder.and(QTaskCustomer.taskCustomer.dialTask.id.eq(request.getTaskId()));
        }
        Iterator<TaskCustomer> iterator = cdrService.findAll(builder).iterator();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LinkedHashMap map = new LinkedHashMap();//表头
        List exportData = new ArrayList<Map>();//数据

        map.put("taskName", "任务名称");
        map.put("name", "客户姓名");
        map.put("idCard", "身份证号");
        map.put("phone", "电话");
        map.put("sex", "性别");
        map.put("botName", "机器人名称");
        map.put("attitude", "客户分类");
        map.put("status", "电话状态");
        map.put("startTime", "呼出时间");
        map.put("answerTime", "接听时间");
        map.put("duration", "呼叫时长");
        map.put("billTime", "通话时长");
        map.put("hangupTime", "挂断时间");
        map.put("endTime", "结束时间");
        while (iterator.hasNext()) {
            TaskCustomer customer = iterator.next();
            Map row = new LinkedHashMap<String, String>();
            row.put("taskName", (Objects.nonNull(customer.getDialTask())) ? customer.getDialTask().getName() : null);
            row.put("name", customer.getName());
            row.put("idCard", customer.getIdCard());
            row.put("phone", customer.getPhone());
            row.put("sex", customer.getSex().equals(Sex.MALE) ? "男" : "女");
            row.put("attitude", (Objects.nonNull(customer.getAttitude())) ? customer.getAttitude().getName() : null);
            row.put("status", customer.getStatus().toString());
            row.put("botName", (Objects.nonNull(customer.getRobotInfo())) ? customer.getRobotInfo().getName() : null);
            row.put("startTime", (customer.getStartTime() != null) ? df.format(customer.getStartTime()) : null);
            row.put("answerTime", (customer.getAnswerTime() != null) ? df.format(customer.getAnswerTime()) : null);
            row.put("duration", (customer.getDuration() != null) ? String.valueOf(customer.getDuration()) : null);
            row.put("billTime", (customer.getBillTime() != null) ? String.valueOf(customer.getBillTime()) : null);
            row.put("hangupTime", (customer.getHangupTime() != null) ? df.format(customer.getHangupTime()) : null);
            row.put("endTime", (customer.getEndTime() != null) ? df.format(customer.getEndTime()) : null);
            exportData.add(row);
        }
        String fileName = String.valueOf(snowflake.next());
        File file = CSVUtils.createCSVFile(exportData, map, rootPath, fileName);
//        File file = new File( rootPath.concat(fileName).concat(".csv"));
        FileUtil.download(response,file);
//        CSVUtils.deleteFile(rootPath.concat(fileName));
    }
}
